package com.tlvip.arithmetic.ch03;


/**
 * <p>description：链表实现</p>
 * <p>copyright： copyright(C)2016-2099</p>
 * <p>Life is short,we need passion</p>
 * <p>Summary： </p>
 * <p>instructions： </p>
 * Date 1/24/21</p>
 * Author mac
 *
 * @version 1.0
 */
public class MyLinkedList {
    // 头节点
    private ListNode head;

    // 链表长度
    private int size;

    /**
     * 插入头部
     *
     * @param data
     */
    public void insertHead(int data) {
        ListNode listNode = new ListNode(data);
        // 栈内存引用
        listNode.setNext(head);
        head = listNode;
        size++;
    }

    /**
     * 插入中间某个位置
     */
    public void insertNth(int data, int position) {
        if (position == 0) {
            insertHead(data);
        } else {
            if (position > size) {
                System.out.println("位置超过链表长度");
                return;
            }
            ListNode current = head;
            for (int i = 1; i < position; i++) {
                current = current.getNext();
            }
            // 创建新节点
            ListNode newNode = new ListNode(data);
            // 新节点的下一个节点指向原当前节点的下一个节点
            newNode.setNext(current.getNext());
            // 当前节点的下一个节点指向新节点
            current.setNext(newNode);
            size++;
        }
    }

    /**
     * 删除头部
     */
    public void deleteHead() {
        head = head.getNext();
        size--;
    }

    /**
     * 删除中间某个值
     */
    public void deleteNth(int position) {
        if (position == 0) {
            deleteHead();
        } else {
            ListNode current = head;
            for (int i = 1; i < position; i++) {
                current = current.getNext();
            }
            current.setNext(current.getNext().getNext());
        }
        size--;
    }

    public void print() {
        ListNode current = head;
        for (int i = 0; i < size; i++) {
            System.out.println(current.getValue());
            current = current.getNext();
        }
        System.out.println("----------");
    }

    public static void main(String[] args) {
        MyLinkedList myLinkedList = new MyLinkedList();
        for (int i = 0; i < 10; i++) {
            myLinkedList.insertNth(i + 9, i);
        }
        myLinkedList.print();

        myLinkedList.deleteHead();
        myLinkedList.print();

        myLinkedList.deleteNth(3);
        myLinkedList.print();
    }

}

class ListNode {
    // 值
    private int value;
    // 下个节点引用
    private ListNode next;

    public ListNode(int value) {
        this.value = value;
        this.next = null;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public ListNode getNext() {
        return next;
    }

    public void setNext(ListNode next) {
        this.next = next;
    }
}
